package com.ruoyi.common.utils.encrypt;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import javax.annotation.PostConstruct;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;

/**
 * description: AES加解密工具类
 * date: 2022年09月05日 16:27
 * author: tmac-1
 * version: 1.0
 */
@Slf4j
@Component
public class AesUtils {
    /**
     * 编码
     */
    private static final String AESCODE = "UTF-8";

    @Autowired
    private Environment env;
    /**
     * 密钥
     */
    public static String key;

    @PostConstruct
    public void readConfig() throws Exception {
        String prefix = "aes.";
        Field[] fields = AesUtils.class.getFields();
        for (Field field : fields) {
            field.set(null, getProperty(prefix + field.getName()));
        }
    }

    private String getProperty(String key) throws UnsupportedEncodingException {
        return new String(env.getProperty(key).getBytes("ISO-8859-1"), "UTF-8");
    }

    /**
     * 生成mysql模式密钥
     *
     * @param encoding
     * @return
     */
    public static SecretKeySpec generateMySQLAESKey(final String encoding) {
        try {
            final byte[] finalKey = new byte[16];
            int i = 0;
            for (byte b : key.getBytes(encoding)) {
                finalKey[i++ % 16] ^= b;
            }
            return new SecretKeySpec(finalKey, "AES");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * AES解密
     *
     * @param data 密文
     * @return
     * @throws Exception
     */
    public static String decrypt(String data) {
        try {
            final Cipher decryptCipher = Cipher.getInstance("AES");
            decryptCipher.init(Cipher.DECRYPT_MODE, generateMySQLAESKey(AESCODE));
            byte[] result = decryptCipher.doFinal(Base64Utils.decode(data.getBytes()));
            return new String(result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * AES加密
     *
     * @param data 待加密内容
     * @return
     * @throws Exception
     */
    public static String encrypt(String data) {
        try {
            final Cipher encryptCipher = Cipher.getInstance("AES");
            encryptCipher.init(Cipher.ENCRYPT_MODE, generateMySQLAESKey(AESCODE));
            byte[] code = Base64Utils.encode(encryptCipher.doFinal(data.getBytes(AESCODE)));
            return new String(code);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
}
